package com.acane.instagram.feature.me

import android.annotation.SuppressLint
import android.util.Log
import android.widget.Toast
import androidx.compose.foundation.Image
import androidx.compose.foundation.background
import androidx.compose.foundation.border
import androidx.compose.foundation.clickable
import androidx.compose.foundation.layout.Arrangement
import androidx.compose.foundation.layout.Box
import androidx.compose.foundation.layout.Column
import androidx.compose.foundation.layout.PaddingValues
import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.Spacer
import androidx.compose.foundation.layout.aspectRatio
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.layout.fillMaxWidth
import androidx.compose.foundation.layout.height
import androidx.compose.foundation.layout.padding
import androidx.compose.foundation.layout.size
import androidx.compose.foundation.layout.width
import androidx.compose.foundation.layout.wrapContentSize
import androidx.compose.foundation.lazy.LazyColumn
import androidx.compose.foundation.lazy.LazyRow
import androidx.compose.foundation.lazy.items
import androidx.compose.foundation.lazy.staggeredgrid.LazyVerticalStaggeredGrid
import androidx.compose.foundation.lazy.staggeredgrid.StaggeredGridCells
import androidx.compose.foundation.lazy.staggeredgrid.items
import androidx.compose.foundation.shape.CircleShape
import androidx.compose.foundation.shape.RoundedCornerShape
import androidx.compose.material.Divider
import androidx.compose.material.ExperimentalMaterialApi
import androidx.compose.material.ModalBottomSheetLayout
import androidx.compose.material.ModalBottomSheetState
import androidx.compose.material.ModalBottomSheetValue
import androidx.compose.material.rememberModalBottomSheetState
import androidx.compose.material3.Button
import androidx.compose.material3.ButtonDefaults
import androidx.compose.material3.Card
import androidx.compose.material3.ExperimentalMaterial3Api
import androidx.compose.material3.IconButton
import androidx.compose.material3.Scaffold
import androidx.compose.material3.Tab
import androidx.compose.material3.TabRow
import androidx.compose.material3.Text
import androidx.compose.material3.TopAppBar
import androidx.compose.material3.TopAppBarDefaults
import androidx.compose.runtime.Composable
import androidx.compose.runtime.LaunchedEffect
import androidx.compose.runtime.collectAsState
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.rememberCoroutineScope
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.graphics.Color
import androidx.compose.ui.graphics.ImageBitmap
import androidx.compose.ui.input.nestedscroll.NestedScrollConnection
import androidx.compose.ui.input.nestedscroll.nestedScroll
import androidx.compose.ui.layout.ContentScale
import androidx.compose.ui.platform.LocalContext
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.text.font.FontWeight
import androidx.compose.ui.tooling.preview.Preview
import androidx.compose.ui.unit.dp
import androidx.compose.ui.unit.sp
import androidx.lifecycle.viewmodel.compose.viewModel
import coil.compose.AsyncImage
import com.acane.instagram.R
import com.acane.instagram.core.config.Config
import com.acane.instagram.core.design.theme.InstagramBlue
import com.acane.instagram.core.design.theme.InstagramLightGray
import com.acane.instagram.core.extension.clickableNoRipple
import com.acane.instagram.core.model.PostInfo
import com.acane.instagram.core.model.UserInfo
import com.acane.instagram.feature.common.SessionManager
import com.acane.instagram.feature.home.HomeViewModel
import com.acane.instagram.feature.login.LoginViewModel
import com.acane.instagram.feature.me.player.VideoPostPlayer
import com.google.accompanist.pager.HorizontalPager
import com.google.accompanist.pager.rememberPagerState
import com.google.accompanist.swiperefresh.SwipeRefresh
import com.google.accompanist.swiperefresh.rememberSwipeRefreshState
import kotlinx.coroutines.CoroutineScope
import kotlinx.coroutines.Dispatchers
import kotlinx.coroutines.launch


@Composable
fun MeRoute(
    toProfile: (String) -> Unit,
    toLogin: () -> Unit,
    toMain: () -> Unit,
    viewModel: HomeViewModel = viewModel(),
    meViewModel: MeViewModel = viewModel(),
    toPost: (String, Int) -> Unit,
    toFollow: (String, String) -> Unit,
    toEditMe: () -> Unit,
    toRegister: () -> Unit,
    toCollection: () -> Unit,
    ) {
    MeScreen(
        viewModel = viewModel,
        meViewModel = meViewModel,
        toLogin = toLogin,
        toMain = toMain,
        toProfile = toProfile,
        toPost = toPost,
        toFollow = toFollow,
        toEditMe = toEditMe,
        toRegister = toRegister,
        toCollection = toCollection
    )
}

@OptIn(ExperimentalMaterialApi::class)
@SuppressLint("StateFlowValueCalledInComposition", "UnusedMaterialScaffoldPaddingParameter",
    "UnusedMaterial3ScaffoldPaddingParameter", "CoroutineCreationDuringComposition",
    "SuspiciousIndentation"
)
@Composable
fun MeScreen(
    viewModel: HomeViewModel,
    meViewModel: MeViewModel,
    loginViewModel: LoginViewModel = viewModel(),
    toLogin: () -> Unit,
    toMain: () -> Unit,
    toProfile: (String) -> Unit,
    toPost: (String, Int) -> Unit,
    toFollow: (String, String) -> Unit,
    toEditMe: () -> Unit,
    toRegister: () -> Unit,
    toCollection: () -> Unit,
) {
    val context = LocalContext.current

    val loggedAccountList = SessionManager.loggedAccountList

    val accountListBottomSheetState = rememberModalBottomSheetState(initialValue = ModalBottomSheetValue.Hidden)

    val addAccountBottomSheetState = rememberModalBottomSheetState(initialValue = ModalBottomSheetValue.Hidden)

    val menuBottomSheetState = rememberModalBottomSheetState(initialValue = ModalBottomSheetValue.Hidden)

    // 管理对话框的显示状态
    var showDialog by remember { mutableStateOf(false) }

    val recommendUserList = viewModel.userDatum.value
    val currentUserInfo = meViewModel.currentUserInfo.collectAsState().value

    // 使用 collectAsState 监听数据流变化
    val gridPostList by meViewModel.gridPostData.collectAsState()
    val videoPostList by meViewModel.videoPostData.collectAsState()


    val (isCardListVisible, setCardListVisible) = remember { mutableStateOf(true) }

    val titles = listOf(
        Pair(R.drawable.grid, R.drawable.grid_unselected),
        Pair(R.drawable.video, R.drawable.video_unselected)
    )
    val nestedScrollConnection = remember {
        object : NestedScrollConnection {}
    }

    val scope = rememberCoroutineScope() // 创建协程作用域

    val refreshState by meViewModel.refresh.collectAsState()

    val swipeRefresh = rememberSwipeRefreshState(isRefreshing = refreshState)
        // 包裹两个 ModalBottomSheetLayout
        Box(modifier = Modifier.fillMaxSize()) {
            // 帐户列表抽屉布局
            ModalBottomSheetLayout(
                sheetState = accountListBottomSheetState,
                sheetShape = RoundedCornerShape(topStart = 10.dp, topEnd = 10.dp),
                sheetContent = {
                    LazyColumn(
                        modifier = Modifier
                            .fillMaxWidth()
                            .padding(top = 1.dp, bottom = 10.dp, start = 10.dp, end = 10.dp)
                    ) {
                        // 添加 Bar
                        item {
                            Box(
                                modifier = Modifier
                                    .fillMaxWidth()
                                    .wrapContentSize(align = Alignment.Center)
                            ) {
                                Image(
                                    painter = painterResource(id = R.drawable.bar_horizontal),
                                    contentDescription = "bar",
                                )
                            }
                        }
                        // 主要内容区域
                        item {
                            Column(modifier = Modifier.padding(10.dp)) {
                                // 账户行
                                loggedAccountList.forEach { account ->
                                    Row(
                                        modifier = Modifier
                                            .fillMaxWidth()
                                            .padding(vertical = 4.dp) // 添加垂直间距
                                    ) {
                                        AsyncImage(
                                            model = account.avatar?.let {
                                                val url = "${Config.ADDRESS}avatars/$it"
                                                Log.d("MeRoute", "🟢 尝试加载头像 URL: $url")
                                                url
                                            },
                                            contentScale = ContentScale.Crop,
                                            contentDescription = "当前登录用户头像",
                                            modifier = Modifier
                                                .size(50.dp)
                                                .clip(CircleShape),
                                            error = painterResource(id = R.drawable.ic_default_avatar) // 加载失败时显示默认
                                        )
                                        // 用户名垂直居中
                                        account.userName?.let {
                                            Text(
                                                text = it,
                                                modifier = Modifier
                                                    .align(Alignment.CenterVertically)
                                                    .padding(start = 10.dp)
                                                    .weight(1f)
                                            )
                                        }
                                        Image(
                                            painter = painterResource(if (account.userName == currentUserInfo.userName) R.drawable.circle_selected else R.drawable.circle_unselected),
                                            contentDescription = "accountList",
                                            modifier = Modifier
                                                .size(30.dp)
                                                .padding(start = 4.dp)
                                                .clip(CircleShape)
                                                .align(Alignment.CenterVertically)
                                                .clickable {
                                                    //切换点击的账号
                                                    scope.launch {
                                                        loginViewModel.login(
                                                            username = account.userName,
                                                            password = account.password,
                                                            toMain = toMain
                                                        )
                                                        // 提示登录成功
                                                        Toast.makeText(context, "登录成功", Toast.LENGTH_SHORT).show()
                                                        accountListBottomSheetState.hide()
                                                    }
                                                }
                                        )
                                    }
                                }
                                // 固定的一行
                                Row(
                                    modifier = Modifier
                                        .fillMaxWidth()
                                        .padding(top = 10.dp)
                                ) {
                                    Image(
                                        painter = painterResource(id = R.drawable.circle_plus),
                                        contentDescription = "addAccount",
                                        modifier = Modifier
                                            .size(50.dp)
                                            .clip(CircleShape)
                                            .clickable {
                                                //弹出底部抽屉
                                                scope.launch {
                                                    //关闭上一个抽屉
                                                    accountListBottomSheetState.hide()
                                                    addAccountBottomSheetState.show()
                                                }
                                                Log.d("ProfilePage", "addAccount clicked")
                                            }
                                    )
                                    Text(
                                        text = "添加账户",
                                        modifier = Modifier
                                            .align(Alignment.CenterVertically)
                                            .padding(start = 10.dp)
                                    )
                                }
                            }
                        }
                    }
                }
            ) {

                SwipeRefresh(state = swipeRefresh, onRefresh = {
                    meViewModel.startRefresh()
                    meViewModel.loadInitialData()
                }) {
                    Scaffold(
                        topBar = {
                            MeTopBar(
                                userInfo = currentUserInfo,
                                coroutineScope = scope,
                                accountListBottomSheetState = accountListBottomSheetState,
                                menuBottomSheetState = menuBottomSheetState,
                            )
                        },
                        modifier = Modifier.nestedScroll(nestedScrollConnection),
                        containerColor = Color.White
                    ) { padding ->
                        Box(
                            modifier = Modifier
                                .padding(padding)
                                .fillMaxSize()
                        ) {
//                            Text(
//                                text = "测试收藏夹",
//                                modifier = Modifier.clickable {
//                                    toCollection()
//                                }
//                            )
                            Column(
                                modifier = Modifier
                                    .fillMaxSize()
                            ) {

                                // 头像和统计信息
                                currentUserInfo.let {
                                    MeProfileHeader(
                                        userInfo = it,
                                        isCardListVisible = isCardListVisible,
                                        setCardListVisible = setCardListVisible,
                                        toFollow = toFollow,
                                        isFollowed = null,
                                        toChat = {  },
                                        toEditMe = toEditMe,
                                    )
                                }

                                // 卡片列表
                                if (isCardListVisible) {
                                    DiscoverUsers(
                                        recommendUserList = recommendUserList,
                                        toProfile = toProfile
                                    )
                                }

                                // TabRow 和 Pager
                                val pagerState = rememberPagerState(initialPage = 0)
                                TabRow(
                                    selectedTabIndex = pagerState.currentPage,
                                    containerColor = Color.White,
                                    tabs = {
                                        titles.forEachIndexed { index, (selectedIcon, unselectedIcon) ->
                                            Tab(
                                                modifier = Modifier.padding(10.dp),
                                                selected = pagerState.currentPage == index,
                                                onClick = {
                                                    scope.launch {
                                                        pagerState.animateScrollToPage(index)
                                                    }
                                                },
                                            ) {
                                                val icon =
                                                    if (pagerState.currentPage == index) selectedIcon else unselectedIcon
                                                Image(
                                                    painter = painterResource(id = icon),
                                                    contentDescription = "Tab Icon",
                                                    modifier = Modifier.size(24.dp)
                                                )
                                            }
                                        }
                                    }
                                )

                                // Pager
                                HorizontalPager(
                                    count = titles.size,
                                    state = pagerState,
                                    modifier = Modifier.weight(1f)
                                ) { page ->
                                    when (page) {
                                        0 -> {
                                            if (gridPostList.isEmpty()) {
                                                Text(
                                                    text = "暂无内容",
                                                    modifier = Modifier.align(Alignment.CenterHorizontally)
                                                )
                                            } else {
                                                PhotoStaggeredGrid(
                                                    coverList = gridPostList,
                                                    viewModel = meViewModel,
                                                    toPost = toPost,
                                                )
                                            }
                                        }

                                        1 -> {
                                            if (videoPostList.isEmpty()) {
                                                Text(
                                                    text = "暂无内容",
                                                    modifier = Modifier.align(Alignment.CenterHorizontally)
                                                )
                                            } else {
                                                VideoPostPlayer(videoPostList.first().urls)
                                            }

                                        }
                                    }
                                }
                                Spacer(Modifier.size(50.dp))
                            }
                        }
                    }
                }

            }
            //添加帐户的抽屉
            ModalBottomSheetLayout(
                sheetState = addAccountBottomSheetState,
                sheetShape = RoundedCornerShape(topStart = 10.dp, topEnd = 10.dp),
                sheetContent = {
                    Column(
                        verticalArrangement = Arrangement.Center,
                        horizontalAlignment = Alignment.CenterHorizontally,
                    ) {
                        Box(
                            modifier = Modifier
                                .fillMaxWidth()
                                .wrapContentSize(align = Alignment.Center)
                        ) {
                            Image(
                                painter = painterResource(id = R.drawable.bar_horizontal),
                                contentDescription = "bar",
                            )
                        }
                        Text(text = "添加帐户")
                        // 分割线
                        Divider(modifier = Modifier
                            .fillMaxWidth()
                            .padding(vertical = 15.dp))
                        Button(
                            onClick = {
                                scope.launch {
                                    //关闭上一个抽屉
                                    addAccountBottomSheetState.hide()
                                    //打开Dialog
                                    showDialog = true
                                }
                            },
                            colors = ButtonDefaults.buttonColors(
                                containerColor = InstagramBlue,
                                contentColor = Color.White
                            ),
                            modifier = Modifier
                                .height(60.dp)
                                .padding(horizontal = 8.dp)
                                .fillMaxWidth(),
                            shape = RoundedCornerShape(5.dp),
                            elevation = ButtonDefaults.buttonElevation(defaultElevation = 0.dp),
                            contentPadding = PaddingValues(horizontal = 8.dp, vertical = 0.dp)
                        ) {
                            Text(
                                text = "登录现有帐户",
                                fontSize = 16.sp,
                                color = Color.White,
                                fontWeight = FontWeight.Bold
                            )
                        }
                        Spacer(modifier = Modifier.height(10.dp))
                        Text(
                            text = "新建帐户",
                            color = InstagramBlue,
                            fontSize = 14.sp,
                            fontWeight = FontWeight.Bold,
                            modifier = Modifier
                                .padding(bottom = 20.dp)
                                .clickable { }
                        )
                    }
                }
            ) { }
            //菜单的抽屉
            ModalBottomSheetLayout(
                sheetState = menuBottomSheetState,
                sheetShape = RoundedCornerShape(topStart = 10.dp, topEnd = 10.dp),
                sheetContent = {
                    Column(
                        verticalArrangement = Arrangement.Center,
                        horizontalAlignment = Alignment.CenterHorizontally,
                    ) {
                        Box(
                            modifier = Modifier
                                .fillMaxWidth()
                                .wrapContentSize(align = Alignment.Center)
                        ) {
                            Image(
                                painter = painterResource(id = R.drawable.bar_horizontal),
                                contentDescription = "bar",
                            )
                        }
                        Row(
                            verticalAlignment = Alignment.CenterVertically,
                            modifier = Modifier
                                .fillMaxWidth()
                                .padding(10.dp)
                                .clickable {
                                    toCollection()
                                    scope.launch {
                                        menuBottomSheetState.hide()
                                    }
                                }
                        ) {
                            Image(
                                painter = painterResource(id = R.drawable.collection),
                                contentDescription = "menu",
                                modifier = Modifier.size(30.dp)
                            )
                            Spacer(modifier = Modifier.width(10.dp))
                            Text(
                                text = "收藏夹",
                                fontSize = 14.sp
                            )
                        }

                    }
                }
            ) { }
            // 根据 showDialog 状态显示对话框
            if (showDialog) {
                SwitchAccountDialog(
                    toLogin = toLogin,
                    onDismissRequest = { showDialog = false },
                    loggedAccountList = loggedAccountList,
                    toRegister = toRegister,
                    toMain = toMain,
                )
            }
        }

}


@Composable
fun MeProfileHeader(
    userInfo: UserInfo,
    isCardListVisible: Boolean,
    setCardListVisible: (Boolean) -> Unit,
    isFollowed: Boolean?,
    toChat: (String) -> Unit,
    toFollow: (String, String) -> Unit,
    toEditMe: () -> Unit,
) {
    Row(

    ) {
        // 头像
        AsyncImage(
            model = userInfo.avatar?.let {
                val url = "${Config.ADDRESS}avatars/$it"
                Log.d("MeRoute", "🟢 尝试加载头像 URL: $url")
                url
            },
            contentScale = ContentScale.Crop,
            contentDescription = "当前用户头像",
            modifier = Modifier
                .padding(end = 40.dp)
                .size(100.dp)
                .clip(shape = CircleShape),
            error = painterResource(id = R.drawable.ic_default_avatar) // 加载失败时显示默认
        )
        // 数据统计
        Column(
            modifier = Modifier
                .padding(top = 10.dp)
        ) {
            Row(
                modifier = Modifier.padding(top = 20.dp),
                horizontalArrangement = Arrangement.SpaceEvenly,
            ) {
                ProfileStats(
                    title = "帖子",
                    count = userInfo.postCount,
                    userId = userInfo.id!!,
                    toFollow = toFollow,
                )
                Spacer(modifier = Modifier.width(50.dp))
                ProfileStats(
                    title = "粉丝",
                    count = userInfo.followerCount,
                    userId = userInfo.id,
                    toFollow = toFollow,
                )
                Spacer(modifier = Modifier.width(50.dp))
                ProfileStats(
                    title = "关注",
                    count = userInfo.followingCount,
                    userId = userInfo.id,
                    toFollow = toFollow,
                )
            }
        }
    }
    Row(

    ) {
        Column(

        ) {
            //简介
            userInfo.introduction?.let {
                Text(
                    text = it, modifier = Modifier
                        .padding(bottom = 5.dp)
                )
            }
            // 昵称
            userInfo.nickName?.let {
                Text(
                    text = it, modifier = Modifier
                        .padding(bottom = 5.dp)
                )
            }
        }

    }
    Row(
        horizontalArrangement = Arrangement.Center
    ) {
        // 按钮
        Button(
            onClick = {
                toEditMe()
            },
            colors = ButtonDefaults.buttonColors(
                containerColor = InstagramLightGray,
                contentColor = Color.Black
            ),
            modifier = Modifier
                .height(30.dp)
                .padding(horizontal = 4.dp)
                .width(170.dp),
            shape = RoundedCornerShape(5.dp),
            elevation = ButtonDefaults.buttonElevation(defaultElevation = 0.dp),
            contentPadding = PaddingValues(horizontal = 8.dp, vertical = 0.dp) // 设置内容内边距
        ) {
            Text(
                text = "编辑主页",
                fontSize = 12.sp,
            )
        }
        Button(
            onClick = {
                toChat(userInfo.userName!!)
            },
            colors = ButtonDefaults.buttonColors(
                containerColor = InstagramLightGray,
                contentColor = Color.Black
            ),
            modifier = Modifier
                .height(30.dp)
                .padding(horizontal = 4.dp)
                .width(170.dp),
            shape = RoundedCornerShape(5.dp),
            elevation = ButtonDefaults.buttonElevation(defaultElevation = 0.dp),
            contentPadding = PaddingValues(horizontal = 8.dp, vertical = 0.dp) // 设置内容内边距
        ) {
            Text(
                text = "分享主页",
                fontSize = 12.sp,
            )
        }

        // 控制卡片隐藏显示的按钮
        IconButton(
            onClick = {
                setCardListVisible(!isCardListVisible)
                Log.d("ProfilePage", "isCardListVisiable: $isCardListVisible")
            },
            modifier = Modifier
                .size(30.dp) // 统一按钮大小
                .clip(RoundedCornerShape(5.dp))
        ) {
            Image(
                painter = painterResource(id = if (isCardListVisible) R.drawable.plus_user_open else R.drawable.plus_user_closed),
                contentDescription = "plus_user",
                modifier = Modifier
                    .size(30.dp)
                    .background(InstagramLightGray)
            )
        }
    }
}
@OptIn(ExperimentalMaterial3Api::class, ExperimentalMaterialApi::class)
@Composable
fun MeTopBar(
    userInfo: UserInfo,
    coroutineScope: CoroutineScope,
    accountListBottomSheetState: ModalBottomSheetState,
    menuBottomSheetState: ModalBottomSheetState,
) {
    TopAppBar(
        title = {},
        navigationIcon = {
            Row(
                modifier = Modifier.padding(end = 8.dp),
                verticalAlignment = Alignment.CenterVertically
            ) {
                userInfo.userName?.let {
                    Text(
                        text = it,
                        fontWeight = FontWeight.Bold,
                        fontSize = 20.sp,
                        modifier = Modifier.padding(top = 10.dp, start = 10.dp)
                    )
                }
                androidx.wear.compose.material3.IconButton(
                    onClick = {
                        // 显示底部抽屉
                        coroutineScope.launch {
                            accountListBottomSheetState.show()
                            Log.d("MeRoute", "accountListBottomSheetState.show()")
                        }
                    },
                    modifier = Modifier
                        .size(30.dp)
                        .padding(start = 10.dp, top = 10.dp)
                ) {
                    Image(
                        painter = painterResource(id = R.drawable.arrow_down),
                        contentDescription = "account"
                    )
                }
            }
        },
        actions = {
            Row {
//                androidx.wear.compose.material3.IconButton(
//                    onClick = {
//                        // 发布帖子
//
//                        Log.d("ProfilePage", "createMedia clicked")
//                    },
//                    modifier = Modifier
//                        .size(45.dp)
//                        .padding(start = 10.dp, end = 10.dp)
//                ) {
//                    Image(
//                        painter = painterResource(id = R.drawable.plus_box),
//                        contentDescription = "createMedia"
//                    )
//                }
                androidx.wear.compose.material3.IconButton(
                    onClick = {
                        coroutineScope.launch {
                            menuBottomSheetState.show()
                        }
                    },
                    modifier = Modifier
                        .size(45.dp)
                        .padding(start = 10.dp, end = 10.dp)
                ) {
                    Image(
                        painter = painterResource(id = R.drawable.menu),
                        contentDescription = "menu"
                    )
                }
            }
        },
        colors = TopAppBarDefaults.centerAlignedTopAppBarColors().copy(
            containerColor = Color.Transparent
        )
    )
}

//推荐用户
@Composable
fun DiscoverUsers(recommendUserList: List<UserInfo>, toProfile: (String) -> Unit) {
    Row(
        modifier = Modifier
            .fillMaxWidth()
            .padding(top = 10.dp, start = 10.dp, end = 10.dp),
        verticalAlignment = Alignment.CenterVertically
    ) {
        if (recommendUserList.isNotEmpty()) {
            Text(text = "发现用户")
            Spacer(modifier = Modifier.weight(1f))
//        Text(text = "显示全部")
        }
    }
    LazyRow(
        modifier = Modifier
            .padding(top = 10.dp, end = 10.dp)
    ) {
        items(recommendUserList, key = { it.id!! }) { recommendUser ->
            Card(
                modifier = Modifier
                    .size(width = 150.dp, height = 250.dp)
                    .padding(5.dp)
                    .background(Color.White)
                    .border(width = 1.dp, color = Color.LightGray, shape = RoundedCornerShape(5.dp)),
                shape = RoundedCornerShape(5.dp),
            ) {
                Box(modifier = Modifier
                    .fillMaxSize()
                    .background(Color.White)) {
                    Column(
                        modifier = Modifier
                            .padding(10.dp)
                            .fillMaxSize(),
                        horizontalAlignment = Alignment.CenterHorizontally,
                    ) {
                        AsyncImage(
                            model = recommendUser.avatar?.let {
                                val url = "${Config.ADDRESS}avatars/$it"
                                Log.d("MeRoute", "🟢 尝试加载封面 URL: $url")
                                url
                            },
                            contentDescription = "推荐用户头像",
                            modifier = Modifier
                                .size(100.dp)
                                .clip(shape = CircleShape)
                                .clickableNoRipple {
                                    toProfile(recommendUser.id!!)
                                },
                            contentScale = ContentScale.Crop,
                            error = painterResource(id = R.drawable.ic_default_avatar) // 加载失败时显示默认
                        )
                        recommendUser.nickName?.let { Text(text = it, fontWeight = FontWeight.Bold) }
                        Text(text = "为你推荐", fontSize = 12.sp)
                        Button(
                            onClick = { },
                            colors = ButtonDefaults.buttonColors(
                                containerColor = Color(0xFF1E90FF),
                                contentColor = Color.White
                            ),
                            shape = RoundedCornerShape(10.dp),
                            modifier = Modifier
                                .padding(top = 25.dp)
                                .width(100.dp)
                        ) {
                            Text(text = "关注")
                        }
                    }
                }
            }
        }
    }
}
@Composable
fun IconBadge(iconRes: Int) {
    Box(
        modifier = Modifier
            .fillMaxSize()
            .padding(8.dp)
    ) {
        Image(
            painter = painterResource(id = iconRes),
            contentDescription = null,
            modifier = Modifier
                .size(24.dp)
                .align(Alignment.TopEnd)
        )
    }
}
@SuppressLint("StateFlowValueCalledInComposition", "CoroutineCreationDuringComposition")
@Composable
fun PhotoStaggeredGrid(
    coverList: List<PostInfo>,
    viewModel: MeViewModel,
    toPost: (String, Int) -> Unit,
) {
    var thumbnailBitmap by remember { mutableStateOf<ImageBitmap?>(null) }
    val coroutineScope = rememberCoroutineScope()
    val context = LocalContext.current
    var postPosition by remember { mutableStateOf(0) }
    LazyVerticalStaggeredGrid(
        columns = StaggeredGridCells.Fixed(3),
        modifier = Modifier.fillMaxSize()
    ) {
        items(coverList) { cover ->
            LaunchedEffect(cover.id) {
                postPosition = viewModel.getPostPosition(cover.id, SessionManager.currentUser?.id!!)
            }
            val url = cover.thumbnailUrl
            Log.d("MeRoute", "🟢 目前封面缩略图 URL: $url")
            Log.d("MeRoute", "🟢 第一个URL: $url")
            val ulrType = viewModel.gridBoxInfo.value[cover]
            Box(modifier = Modifier.aspectRatio(1f)) {
                // 公共图片加载部分
                if (url.endsWith(".mp4")) {
                    val videoUrl = "${Config.ADDRESS}video/$url"
                    LaunchedEffect(videoUrl) {
                        coroutineScope.launch(Dispatchers.IO) {
                            thumbnailBitmap =
                                viewModel.generateVideoThumbnail(context, videoUrl).also {
                                    if (it == null) {
                                        Log.d("MeRoute", "🟢 缩略图生成失败: $videoUrl")
                                    }
                                }
                        }
                    }
                    // 显示缩略图
                    thumbnailBitmap?.let { bitmap ->
                        Log.d("MeRoute", "🟢 缩略图生成成功: $videoUrl")
                        Image(
                            bitmap = bitmap,
                            contentDescription = "视频缩略图",
                            modifier = Modifier
                                .fillMaxSize()
                                .clickable {
                                    toPost(cover.user.id!!, postPosition)
                                },
                            contentScale = ContentScale.Crop,
                        )
                    }?: run {
                        Log.d("MeRoute", "🟢 缩略图生成失败: $videoUrl")
                        // 显示默认占位图
                        Image(
                            painter = painterResource(id = R.drawable.ic_default_avatar),
                            contentDescription = "默认占位图",
                            modifier = Modifier
                                .fillMaxSize()
                                .clickable {
                                    toPost(cover.user.id!!, postPosition)
                                },
                            contentScale = ContentScale.Crop,
                        )
                    }
                } else {
                    AsyncImage(
                        model = "${Config.ADDRESS}avatars/$url",
                        contentDescription = "帖子封面",
                        contentScale = ContentScale.Crop,
                        modifier = Modifier
                            .fillMaxSize()
                            .clickable {
                                toPost(cover.user.id!!, postPosition)
                            },
                        error = painterResource(id = R.drawable.ic_default_avatar)
                    )
                }

                // 根据类型叠加图标
                when (ulrType) {
                    "isGrid" -> IconBadge(iconRes = R.drawable.square_multiple)
                    "isVideo" -> IconBadge(iconRes = R.drawable.video_unselected)
                }
            }
        }
    }
}

@Composable
fun ProfileStats(
    title: String,
    count: Int,
    userId: String,
    toFollow: (String, String) -> Unit,
) {

    Column(
        modifier = Modifier
            .clickable {
                // 跳转到Follow页面
                if (title == "帖子") {
                    return@clickable
                }
                toFollow(userId, title)
            },
        horizontalAlignment = Alignment.CenterHorizontally,
        verticalArrangement = Arrangement.Center,
    ) {
        Text(
            text = count.toString(),
            fontWeight = FontWeight.Bold
        )
        Text(
            text = title,
        )
    }
}
@Preview
@Composable
fun MeScreenPreview() {
    //MeRoute()

}